using log4net.Config;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using OConf.API.Filter;
using OConf.API.Header;
using OConf.API.hub;
using OConf.API.Middleware;
using OConf.BLL;
using OConf.IBLL;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace OConf.API
{
    public class Startup
    {
        public readonly string anyAllowSpecificOrigins = "any";//解决跨域

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;

            //配置日志
            XmlConfigurator.Configure();
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            //解决跨域
            services.AddCors(options =>
            {
                options.AddPolicy(anyAllowSpecificOrigins, corsbuilder =>
                {
                    var corsList = Configuration.GetSection("CorsAccessorSettings:WithOrigin").GetChildren().ToList();
                    List<string> corsPaths = new List<string>();
                    foreach (var item in corsList)
                    {
                        corsPaths.Add(item.Value);
                    }
                    corsbuilder.WithOrigins(corsPaths.ToArray())
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials();//指定处理cookie
                });
            });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "OConf.API", Version = "v1" });

                string apiXml = Path.Combine(AppContext.BaseDirectory, "OConf.API.xml");
                string modelXml = Path.Combine(AppContext.BaseDirectory, "OConf.Model.xml");

                c.IncludeXmlComments(apiXml, true);
                c.IncludeXmlComments(modelXml, true);
                c.OrderActionsBy(o => o.RelativePath);//文档内容按接口名称排序
            });

            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

            //JWT验证服务注入
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                //获取JWT配置信息
                JWTConfigModel.ValidateIssuerSigningKey = Convert.ToBoolean(Configuration["JWTTokenOptions:ValidateIssuerSigningKey"]);
                JWTConfigModel.SecurityKey = Configuration["JWTTokenOptions:SecurityKey"];
                JWTConfigModel.ValidateAudience = Convert.ToBoolean(Configuration["JWTTokenOptions:ValidateAudience"]);
                JWTConfigModel.Audience = Configuration["JWTTokenOptions:Audience"];
                JWTConfigModel.ValidateIssuer = Convert.ToBoolean(Configuration["JWTTokenOptions:ValidateIssuer"]);
                JWTConfigModel.Issuer = Configuration["JWTTokenOptions:Issuer"];
                JWTConfigModel.ValidateLifetime = Convert.ToBoolean(Configuration["JWTTokenOptions:ValidateLifetime"]);
                JWTConfigModel.ExpiredTime = Convert.ToInt64(Configuration["JWTTokenOptions:ExpiredTime"]);

                options.SaveToken = true;
                options.RequireHttpsMetadata = false;
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuerSigningKey = JWTConfigModel.ValidateIssuerSigningKey,    //是否验证秘钥
                    ValidateAudience = JWTConfigModel.ValidateAudience,    //是否验证Audience
                    ValidateIssuer = JWTConfigModel.ValidateIssuer,      //是否验证Issuer
                    ValidateLifetime = JWTConfigModel.ValidateLifetime,    //是否验证失效时间
                    ValidAudience = JWTConfigModel.Audience,
                    ValidIssuer = JWTConfigModel.Issuer,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JWTConfigModel.SecurityKey))
                };
            });

            services.AddScoped<IProjectInfoBLL, ProjectInfoBLL>();
            services.AddScoped<IConfigInfoBLL, ConfigInfoBLL>();
            services.AddScoped<ICNameSpaceBLL, CNameSpaceBLL>();
            services.AddScoped<IAdminBLL, AdminBLL>();
            services.AddScoped<ILoginLogBLL, LoginLogBLL>();
            services.AddScoped<IVersionsBLL, VersionsBLL>();

            //Dto参数验证
            services.AddMvc(options =>
            {
                options.Filters.Add<RequestParamActionFilter>();
            }).AddJsonOptions(options =>
            {
                //格式化日期时间格式
                options.JsonSerializerOptions.Converters.Add(new DatetimeJsonConverter());

                //反序列化过程中属性名称是否使用不区分大小写的比较
                options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
            });
            services.Configure<ApiBehaviorOptions>(options =>
            {
                // 使用自定义模型验证【Api接口需要添加才能生效】
                options.SuppressModelStateInvalidFilter = true;
            });

            services.AddSignalR();
            services.AddSingleton<IUserIdProvider, AppUserIdProvider>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "OConf.API v1"));
            }

            //允许body重用
            app.Use(next => context =>
            {
                context.Request.EnableBuffering();
                return next(context);
            });

            app.UseHttpsRedirection();

            app.UseRouting();

            //认证中间件
            app.UseAuthentication();

            //支持跨域：允许特定来源的主机访问
            app.UseCors(anyAllowSpecificOrigins);

            //授权中间件
            app.UseAuthorization();

            app.UseAuthMiddleware();

            app.UseStaticFiles();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapHub<ChatHub>("/chat");
                endpoints.MapControllers().RequireCors(anyAllowSpecificOrigins);
            });
        }

        
    }
}